package org.hank.compose_yyzs.ui.widget.dialog

import android.view.Gravity
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.DialogWindowProvider
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.bean.WifiBean
import org.hank.compose_yyzs.db.dao.WifiDao
import org.hank.compose_yyzs.ui.theme.AppTheme
import org.hank.compose_yyzs.utils.getString
import javax.inject.Inject


//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/9/9 10:24
 *描述:
 */

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun WifiHistoryDialog(
    showState: MutableState<Boolean>,
    onUpdateWifi: () -> Unit = { },
    onItemClickListener: (WifiBean) -> Unit
) {
    var context = LocalContext.current
    var viewModel: WifiHistoryViewModel = hiltViewModel()
    var scope = rememberCoroutineScope()
    var scrollState = rememberLazyListState()
    var wifiAllState: State<List<WifiBean>> = viewModel.wifiAll.collectAsStateWithLifecycle()
    var showDelTips by remember { mutableStateOf(false) }

    LaunchedEffect(true) {
        scope.launch(Dispatchers.IO) {
            viewModel.getWifiHistory()
        }
    }

    DialogCenter(showState) {
        Surface(shape = MaterialTheme.shapes.large) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(MaterialTheme.colorScheme.background),
            ) {
                Box(modifier = Modifier.fillMaxWidth()) {
                    Image(
                        painter = painterResource(id = R.mipmap.ic_return_black),
                        contentDescription = "",
                        modifier = Modifier
                            .align(
                                Alignment.CenterStart
                            )
                            .padding(start = 16.dp)
                            .clickable {
                                showState.value = false
                            }
                    )
                    Text(
                        modifier = Modifier
                            .padding(top = 16.dp, bottom = 16.dp)
                            .align(Alignment.Center),
                        text = context.getString(R.string.setting_wifi_history),
                        style = MaterialTheme.typography.titleMedium,
                        textAlign = TextAlign.Center
                    )
                }
                Divider(thickness = 1.dp, color = AppTheme.colors.divider)
                LazyColumn(modifier = Modifier.height(240.dp), state = scrollState) {
                    if (wifiAllState.value?.size == 0) {
                        item {
                            Column {
                                Divider(thickness = 1.dp, color = AppTheme.colors.divider)
                                Spacer(modifier = Modifier.height(4.dp))
                                Box(modifier = Modifier.fillMaxSize()) {
                                    Image(
                                        painter = painterResource(id = R.mipmap.ic_nodata),
                                        contentDescription = "",
                                        contentScale = ContentScale.Crop,
                                        modifier = Modifier.fillMaxSize()
                                    )
                                    Text(
                                        text = getString(resourceId = R.string.adapter_no_data),
                                        modifier = Modifier
                                            .align(
                                                Alignment.BottomCenter
                                            )
                                            .padding(bottom = 32.dp)
                                    )
                                }
                            }
                        }
                    } else {
                        items(items = wifiAllState.value) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .combinedClickable(
                                        onLongClick = {
                                            viewModel.selectWifiPosition.value =
                                                wifiAllState.value.indexOf(it)
                                            showDelTips = true
                                        }) {
                                        onItemClickListener.invoke(it)
                                    }
                                    .padding(16.dp)
                            ) {
                                Text(text = it.wifiName, modifier = Modifier.weight(1f))
                                if (it.isCurrentWifi) {
                                    Image(
                                        painter = painterResource(id = R.mipmap.ic_wifi),
                                        contentDescription = ""
                                    )
                                }
                            }
                            Divider(thickness = 1.dp, color = AppTheme.colors.divider)
                        }
                    }
                }
                LaunchedEffect(true) {
                    while (scrollState.layoutInfo.visibleItemsInfo.size <= 1)
                        delay(100)
                    scrollState.scrollToItem(viewModel.getCurrentPosition())
                }
                Spacer(modifier = Modifier.height(16.dp))
            }
        }

        if (showDelTips) {
            TipsDialog(tipsString = getString(resourceId = R.string.setting_wifi_del_tips), true, {
                showDelTips = false
            }) {
                showDelTips = false
                scope.launch {
                    var job = viewModel.delHistory()
                    var ret = job?.await()
                    if ((ret ?: 0) == 1) {
                        viewModel.getWifiHistory()
                        delay(100)
                        onUpdateWifi.invoke()
                    }
                }
            }
        }
    }
}

@Composable
fun DialogCenter(
    showState: MutableState<Boolean>,
    dismissRequest: () -> Unit = {},
    content: @Composable () -> Unit
) {
    if (showState.value) {
        Dialog(
            onDismissRequest = {
                dismissRequest.invoke()
                showState.value = false
            },
            properties = DialogProperties(
                dismissOnClickOutside = true
            )
        ) {
            val dialogWindowProvider = LocalView.current.parent as DialogWindowProvider
            dialogWindowProvider.window.setGravity(Gravity.CENTER)
            content()
        }
    }
}


@HiltViewModel
class WifiHistoryViewModel @Inject constructor(var wifiDao: WifiDao) : ViewModel() {
    var wifiAll: MutableStateFlow<List<WifiBean>> = MutableStateFlow(emptyList())
    var selectWifiPosition = MutableStateFlow(-1)
    fun getWifiHistory() {
        viewModelScope.launch(Dispatchers.IO) {
            wifiAll.emit(wifiDao.allWifiInfo.stateIn(scope = viewModelScope).value ?: emptyList())
        }
    }

    fun getCurrentPosition(): Int {
        for (i in 0 until wifiAll.value.size) {
            if (wifiAll.value[i].isCurrentWifi)
                return i
        }
        return 0
    }

    fun delHistory(): Deferred<Int>? {
        if (selectWifiPosition.value != -1) {
            return viewModelScope.async(Dispatchers.IO) {
                var wifiBean = wifiAll.value[selectWifiPosition.value]
                wifiDao.delWifiInfo(wifiBean)
            }
        } else
            return null
    }
}